package com.rjj.websocket.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * @author renjianjun
 * @date 2020-06-26 09:50
 * @Email:215060580@qq.com
 */
@Controller
public class IndexController {

    /**
     *  可以甚至多个参数
     */
    @RequestMapping({"/","index","index.html"})
    public String index(HttpServletRequest request, Map<String,String> map){
        request.setAttribute("method","mysocket");
        //localhost:8080
        String localAddr = request.getServerName() + ":" + request.getServerPort();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String url = "ws://" + localAddr + "/mysocket/"+uuid;
        map.put("url",url);
        map.put("uuid",uuid);
        return "index";
    }

    /**
     * 前端姓名的改变
     */
    @RequestMapping("changeName")
    @ResponseBody
    public String changeName(@RequestParam(name = "name") String name,@RequestParam(name = "uuid") String uuid){
        Websocket.nameMap.put(uuid,name);
        return "ok";
    }

    /**
     * 获取cookie
     * @param name cookie名称
     * @param defaultValue 默认值
     * @param request 请求对象
     */
    public String getCookie(String name, String defaultValue, HttpServletRequest request) {
        Cookie cookie = this.getCookieObject(name,request);
        return cookie != null ? cookie.getValue() : defaultValue;
    }

    public Cookie getCookieObject(String name,HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
